﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Contract;
using System.Threading;
using System.Net;

namespace ConsoleApplication1
{
    class Program
    {
        private List<IPAddress> agentsIP = new List<IPAddress>();
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(Service_Allocation));

            NetTcpBinding binding = new NetTcpBinding();
            binding.TransferMode = TransferMode.Streamed;
            binding.ReceiveTimeout = TimeSpan.MaxValue;
            binding.MaxReceivedMessageSize = long.MaxValue;

            host.AddServiceEndpoint(typeof(IService_Allocation), binding,
            new Uri("net.tcp://localhost:8888/Service_Allocation"));

            host.Open();

            Console.WriteLine("Main thread: starting a timer");
            Timer t = new Timer(ComputeBoundOp, null, 0, 10000);
                //(ComputeBoundOp, 5, 0, 2000);
            //Console.WriteLine("Main thread: Doing other work here...");
            //Thread.Sleep(10000); // Simulating other work (10 seconds)
            //t.Dispose(); // Cancel the timer now
        }
        // This method's signature must match the TimerCallback delega
        private static IPAddress ComputeBoundOp(Object state)
        {
            NetTcpBinding binding = new NetTcpBinding();
            binding.TransferMode = TransferMode.Streamed;
            binding.MaxReceivedMessageSize = 200000000000000;
            binding.SendTimeout = TimeSpan.MaxValue;
            EndpointAddress address = new EndpointAddress("net.tcp://" + agentsIP[0].ToString() + ":8000/DataUploader");
            ChannelFactory<IDataUploader> channel =
                    new ChannelFactory<IDataUploader>(binding, address);
            IDataUploader Proxy = channel.CreateChannel();
            IPAddress targetAgent = agentsIP[0];
            int con = Proxy.returnNumOfConnections();

            foreach (IPAddress ip in agentsIP)
            {
                address = new EndpointAddress("net.tcp://" + ip.ToString() + ":8000/DataUploader");
                channel = new ChannelFactory<IDataUploader>(binding, address);
                Proxy = channel.CreateChannel();

                if (con >= Proxy.returnNumOfConnections())
                {
                    targetAgent = ip;
                }
                con = Proxy.returnNumOfConnections();

            }
            return targetAgent;
        }
    }
}
